import { _decorator, Component, Collider2D, IPhysics2DContact, Contact2DType, Vec2, RigidBody2D, ERigidBody2DType, PhysicsSystem2D } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('SpringCollider')
export class SpringCollider extends Component {
    @property
    bounceForce: number = 200; // 弹力大小
    
    private rb: RigidBody2D | null = null;
    private collider: Collider2D | null = null;

    protected onLoad(): void {
        this.rb = this.node.getComponent(RigidBody2D);
        if(!this.rb){
            this.rb = this.node.addComponent(RigidBody2D);
            this.rb.enabled = false;
            this.rb.enabledContactListener = true;
            this.rb.type = ERigidBody2DType.Static; 
            this.rb.enabled = true;
        }
    }
    
    start() {
        this.collider = this.getComponent(Collider2D);
        console.log(this.collider)
        if (this.collider) {
            this.collider.sensor = true;
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            this.node.active = false;
            this.node.active = true;
            console.log("添加了SpringCollider碰撞器")
        }
    }

    protected update(dt: number): void {
    }
 
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        const otherRigidBody = otherCollider.getComponent(RigidBody2D);
        console.log("触发 -> 弹簧selfCollider", selfCollider.node.name)
        console.log("触发 -> 弹簧otherCollider", otherCollider.node.name)
        
        if (otherRigidBody) {
            // 计算弹跳方向(垂直向上)
            const bounceDirection = new Vec2(0, 1);
            otherRigidBody.linearVelocity = new Vec2(0, 0); // 重置速度
            otherRigidBody.applyForceToCenter(bounceDirection.multiplyScalar(this.bounceForce), true);
        }
    }
}